package com.wolf.server;

import com.wolf.core.BeanMethod;
import com.wolf.core.RequestEntity;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @auth: dylan
 * @Desc:
 * @Time: 2024/5/2
 */
public class BeanDispatcher {

    private volatile static BeanDispatcher INSTANCE;
    public  final ConcurrentHashMap<String, BeanMethod> BEAN_METHOD_CONTAINER=new ConcurrentHashMap<>();
    //私有化构造
    private BeanDispatcher(){}

    public static BeanDispatcher getInstance(){
        if(null==INSTANCE){
            synchronized (BeanDispatcher.class){
                if(null==INSTANCE){
                    INSTANCE=new BeanDispatcher();
                }
            }
        }
        return INSTANCE;
    }

    /***
     *@DESC 具体执行的方法
     *@params [request]
     *@返回值 java.lang.Object
     *@author dylan
     *@Date 2024/5/2
     */
    public  Object process(RequestEntity request) throws InvocationTargetException, IllegalAccessException {
        String key=request.getClazz().getName()+"."+request.getMethodName();
        BeanMethod beanMethod = BEAN_METHOD_CONTAINER.get(key);
        if(null==beanMethod){
            throw new RuntimeException("Not found Method "+key);
        }
        Method method = beanMethod.getMethod();
        Object result = method.invoke(beanMethod.getBean(), request.getParams());
        return result;
    }
}
